package com.leyantech.ecp.agenx.session.client;

import com.leyantech.ecp.agenx.proto.AssistantInfo;
import com.leyantech.ecp.agenx.proto.GetOnlineAssistantsByStoreRequest;
import com.leyantech.ecp.agenx.proto.GetOnlineAssistantsByStoreResponse;
import com.leyantech.ecp.agenx.proto.SessionManagerGrpc.SessionManagerBlockingStub;
import com.leyantech.utility.Logger;
import com.leyantech.utility.protobuf.JsonFormatUtils;

import com.google.common.cache.CacheLoader;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-17.
 */
@Singleton
public class SessionManagerLoader extends CacheLoader<String, Set<Assistant>> {

  private final Logger logger = new Logger(SessionManagerLoader.class);

  private final SessionManagerBlockingStub stub;

  @Inject
  public SessionManagerLoader(SessionManagerBlockingStub stub) {
    this.stub = stub;
  }

  @Override
  public Set<Assistant> load(@Nonnull String storeId) {
    final GetOnlineAssistantsByStoreRequest request = GetOnlineAssistantsByStoreRequest
        .newBuilder()
        .setStoreId(storeId)
        .build();
    try {
      logger.info("GetOnlineAssistantsByStoreRequest storeId {}", storeId);

      final GetOnlineAssistantsByStoreResponse response = stub
          .getOnlineAssistantsByStore(request);
      logger.info("GetOnlineAssistantsByStoreRequest response {}",
          JsonFormatUtils.asOneLinerJson(response));

      return response.getAssistantInfoList()
          .stream()
          .map(assistant -> fromProtobuf(storeId, assistant))
          .collect(Collectors.toCollection(Sets::newConcurrentHashSet));
    } catch (Exception e) {
      logger.error("GetOnlineAssistantsByStoreRequest error, storeId {}", storeId, e);
      throw e;
    }
  }

  private Assistant fromProtobuf(String storeId, AssistantInfo assistantInfo) {
    return Assistant.builder()
        .storeId(storeId)
        .assistantId(assistantInfo.getAssistantId())
        .assistantName(assistantInfo.getAssistantNick())
        .clientUuid(assistantInfo.getDeviceNo())
        .clientVersion(assistantInfo.getClientVersion())
        .functionList(assistantInfo.getServiceFuncListList())
        .serviceMode(assistantInfo.getServiceMode())
        .timestamp(assistantInfo.getTimestamp())
        .action(assistantInfo.getAction())
        .status(assistantInfo.getServerStatus())
        .nodeId(assistantInfo.getNodeId())
        .build();
  }

}
